package com.liziyi0914.morearmor.effect;

import com.liziyi0914.morearmor.PlayerManager;
import com.liziyi0914.morearmor.Utils;
import com.liziyi0914.morearmor.event.Listener;
import com.liziyi0914.morearmor.event.entity.WorldTickEvent;
import net.minecraft.block.Blocks;
import net.minecraft.entity.Entity;
import net.minecraft.entity.LivingEntity;
import net.minecraft.item.Items;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.util.math.Box;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.World;

import java.util.HashMap;
import java.util.UUID;
import java.util.function.Predicate;

public class CobwebEffect extends AbstractEffect {

    HashMap<UUID, Long> record = new HashMap<>();

    @Listener
    public void onTick(WorldTickEvent e) {
        for (Entity entity : e.getWorld().getEntities()) {
            if (entity instanceof LivingEntity livingEntity) {
                if (!predicateArmor().test(livingEntity)) {
                    continue;
                }
                Vec3d p = livingEntity.getPos();
                final ServerPlayerEntity playerEntity = PlayerManager.get(entity.getUuid());
                if (playerEntity == null) continue;
                World world = playerEntity.getServerWorld();
                world.getOtherEntities(playerEntity, new Box(p.getX() - 5, p.getY() - 5, p.getZ() - 5, p.getX() + 5, p.getY() + 5, p.getZ() + 5), en -> entity.getPos().distanceTo(en.getPos()) < 5)
                        .forEach(en -> {
                            if (!(en instanceof LivingEntity living) || en.getUuid().equals(playerEntity.getUuid())) {
                                return;
                            }
                            long time = record.getOrDefault(playerEntity.getUuid(), 0L);
                            if (System.currentTimeMillis() - time >= 1000) {
                                record.put(playerEntity.getUuid(), System.currentTimeMillis());
                                world.setBlockState(living.getBlockPos(), Blocks.COBWEB.getDefaultState());
                            }
                        });
            }
        }
    }

    @Override
    public Predicate<LivingEntity> predicateArmor() {
        return Utils.hasItemArmor(Items.COBWEB);
    }
}
